package org.jef.core.util;

import java.util.UUID;

/**
 * @version 1.0
 * @description: 生成随机字符
 * @author: ChengZhi 0336
 * @create: 2024-10-09 16:35
 **/
public class RandStrUtils {

    /**
     * 根据表达式生成随机字符，用于指定字符后拼接随机内容
     * @param str  例如：掼友-?{9}
     * @return     例如：掼友-f9277c45-
     */
    public static String getRandomStr(String str) {
        String uuid = UUID.randomUUID().toString();
        int n;
        while ((n=str.indexOf("?{"))>-1) {

            int m = str.indexOf("}",n);
            if (n > -1 && m > -1) {
                // 表达式
                String expression = str.substring(n+2, m);
                Integer length = Integer.valueOf(expression);
                if (uuid.length() > length) {
                    uuid = uuid.substring(0,length);
                }
                StringBuilder sb = new StringBuilder(str.length());
                sb.append(str.substring(0, n));
                sb.append(uuid);
                sb.append(str.substring(m+1));
                str = sb.toString();
            }
        }

        return str;
    }
}
